using System.Data;
using Publicuse.Cache;
using Publicuse.Entity;
using Publicuse.Interface;
using Publicuse.Util;

namespace Geekeradmin.ExtendsService
{
  public class DatacacheService : BackgroundService
  {
    private readonly IMySqlSugarService mySqlSugar;
    private static bool isfirst = true;

    /// <summary>
    /// 初始化依赖注入
    /// </summary>
    /// <param name="mySqlSugar"></param>
    public DatacacheService(IMySqlSugarService mySqlSugar)
    {
      this.mySqlSugar = mySqlSugar;
    }

    public override async Task StartAsync(CancellationToken cancellationToken)
    {
      await base.StartAsync(cancellationToken);
    }

    public override async Task StopAsync(CancellationToken cancellationToken)
    {
      await base.StopAsync(cancellationToken);
    }

    public override void Dispose() { }

    /// <summary>
    ///
    /// </summary>
    /// <param name="stoppingToken"></param>
    /// <returns></returns>
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
      try
      {
        while (!stoppingToken.IsCancellationRequested)
        {
          await Task.Delay(12000, stoppingToken); //启动后一分钟执行一次
          InitTask();
        }
      }
      catch (Exception ex) { }
    }

    private void InitTask()
    {
      Task.Factory.StartNew(() =>
      {
        if (isfirst)
        {
          isfirst = false;
          UserAuthorCache.AddUsercache(this.mySqlSugar);
          UserAuthorCache.AddRolecache(this.mySqlSugar);
          UserAuthorCache.AddUserRolecache(this.mySqlSugar);
          UserAuthorCache.AddAuthorcache(this.mySqlSugar);
          UserAuthorCache.AddURMcache(this.mySqlSugar);
          UserAuthorCache.AddRoleRescache(this.mySqlSugar);
          UserAuthorCache.AddDictionariescache(this.mySqlSugar);
        }
      });
    }
  }
}
